<script setup>
import { computed, onMounted, reactive, ref, watchEffect } from 'vue';
import data from "@/untils/address/states.json"
const formLabelWidth = '100px'
//  import dayjs from "dayjs"
import { ElMessage } from 'element-plus'
import phoneCodeList from "@/untils/phonecode/countryCallingCodes.json"
// import { addclassinfo,updateClass } from '../../api/request';
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import axios from 'axios';
// import { addarea ,addschoolbasics,updateClass, updateschoolbasics} from '../../api/request';
import dayjs from 'dayjs';
import { Decrypt, Encrypt } from '../../untils/passjs/security';
import { AddSupplierData, getRoledata, updateSupplier, getRoledataList, distributorDropDownapi } from '../../api/api';
let formRef = ref(null)
let props = defineProps({
    dialogFormVisible: Boolean,
    formlist: Object,
    changeType: String
})
// 国家列表数据
const datasel = ref([]);

// 州/省列表数据
const states = ref([]);
// 国家与州/省的映射关系
const countryStates = ref({});
// watchEffect(()=>{
//     props.formlist.contry = toString(props.formlist.area).split("/")[0]
//     props.formlist.addresszhou = toString(props.formlist.area).split("/")[1]
// })
let distributorDropDownList = ref([])
let isAdmin = ref(false)
watchEffect(async () => {
    if (props.dialogFormVisible) {
        const userRoles = JSON.parse(localStorage.getItem('userdetail'))?.roles || [];
        isAdmin.value = userRoles.some(role => role.roleName === 'admin' || role.roleName === 'SuperAdmin');
        console.log('Is Admin?', isAdmin.value);
        if (!isAdmin.value) {
            return;
        }
        try {
            let res = await distributorDropDownapi()
            console.log(res);
            if (res.code == 200) {
                // distributorDropDownList.value = res.data
                let newarr = res.data.filter(item => item.userLevel !== 9);
                distributorDropDownList.value = newarr

            }
        } catch (error) {
            console.log(error);

        }

    }

})
onMounted(() => {
    datasel.value = data.data;
    const tempCountryStates = {};
    data.data.forEach(country => {
        tempCountryStates[country.name] = country.states || [];
    });
    countryStates.value = tempCountryStates;
})
const handleCountryChange = (countryName) => {
    props.formlist.addresszhou = '';
    states.value = countryStates.value[countryName] || [];
};
let emits = defineEmits(["close", 'update:formlist'])
function closedialog(formEl) {
    if (!formEl) return
    emits("close")
}
async function addsubmit(formEl) {
    if (props.changeType == "add") {
        if (props.formlist.username == '' || props.formlist.password == '' || props.formlist.nickname == '' || props.formlist.email == '' || props.formlist.phone == '' || props.formlist.gender == null || props.formlist.contry == '' || props.formlist.addresszhou === '' || props.formlist.phoneAreaCode == '') {
            ElMessage.warning("Please enter complete user information")
            return;
        }
        console.log(props.formlist, "新增数据");
        const selectedCountry = props.formlist.contry;
        const selectedState = props.formlist.addresszhou;
        const selectedCountryData = data.data.find(country => country.name === selectedCountry);
        const selectedStateData = selectedCountryData?.states?.find(state => state.name === selectedState);
        if (selectedCountry && selectedState) {
            const countryStateCode = selectedCountryData.state_code;
            const stateStateCode = selectedStateData?.state_code;
            props.formlist.area = `${countryStateCode}/${stateStateCode}`
            let requestData = {
                username: props.formlist.username,
                password: props.formlist.password,
                nickname: props.formlist.nickname,
                email: props.formlist.email,
                phone: props.formlist.phone,
                gender: props.formlist.gender,
                area: props.formlist.area,
                address: props.formlist.account,
                phoneAreaCode: props.formlist.phoneAreaCode,
                parentId: props.formlist.parentId
            }
            try {
                let res = await AddSupplierData(Encrypt(JSON.stringify(requestData)))
                console.log(res);
                if (res.code == 200) {
                    ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                    emits("close")
                }
            } catch (error) {
                console.log(error);

            }
        }
    } else if (props.changeType == "update") {
        if (props.formlist.nickname == '' || props.formlist.email == '' || props.formlist.phone == '' || props.formlist.gender == null || props.formlist.contry == '' || props.formlist.addresszhou === '' | props.formlist.phoneAreaCode == '') {
            ElMessage.warning("Please enter complete user information")
            return;
        }
        console.log(props.formlist, "编辑数据");
        const selectedCountry = props.formlist.contry;
        const selectedState = props.formlist.addresszhou;
        const selectedCountryData = data.data.find(country => country.name === selectedCountry);
        const selectedStateData = selectedCountryData?.states?.find(state => state.name === selectedState);

        if (selectedCountry && selectedState) {
            const countryStateCode = selectedCountryData.state_code;
            const stateStateCode = selectedStateData?.state_code;
            props.formlist.area = `${countryStateCode}/${stateStateCode}`
            let requestData = {
                userId: props.formlist.userId,
                email: props.formlist.email,
                phone: props.formlist.phone,
                nickname: props.formlist.nickname,
                gender: props.formlist.gender,
                area: props.formlist.area,
                address: props.formlist.account,
                userLevel: props.formlist.userLevel,
                roleIds: props.formlist.roleName,
                phoneAreaCode: props.formlist.phoneAreaCode
            }
            console.log(Encrypt(JSON.stringify(requestData)));
            console.log(Decrypt(Encrypt(JSON.stringify(requestData))));
            try {
                let res = await updateSupplier(requestData)
                console.log(res, "修改");
                if (res.code == 200) {
                    ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                    closedialog(formEl)
                }
            } catch (error) {
                console.log(error);
            }
        }
    }
}
let roleOptions = ref([])
let adminrule = ref({
    username: [
        {
            required: true,
            message: 'Please input a username',
            trigger: 'blur'
        },
        {
            pattern: /^[a-zA-Z0-9]{8,16}$/,
            message: 'The account requires a combination of 8-16 letters or numbers',
            trigger: 'blur'
        }
    ],
    password: [
        {
            required: true,
            message: 'Please input a password',
            trigger: 'blur'
        },
        {
            pattern: /^(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])[A-Za-z\d!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,16}$/,
            message: 'requires a combination of 8-16 letters or numbers',
            trigger: 'blur'
        }
    ],
    nickname: [
        {
            required: true,
            message: 'Please input a nickname',
            trigger: 'blur'
        },
    ],
    email: [
        {
            required: true,
            message: 'Please input a email',
            trigger: 'blur'
        },
    ],
    phone: [
        {
            required: true,
            message: 'Please input a phone',
            trigger: 'blur'
        },
    ],
    gender: [
        {
            required: true,
            message: 'Please input a gender',
            trigger: 'blur'
        },
    ],
    area: [
        {
        },
    ],
    contry: [
        {
            required: true,
            message: 'Please select your contry',
            trigger: 'blur'
        },
    ],
    addresszhou: [
        {
            required: true,
            message: 'Please select your addresszhou',
            trigger: 'blur'
        },
    ],
    roleName: [
        {
            required: true,
            message: 'Please select your roleName',
            trigger: 'change'
        }
    ],
    parentId: [
        {
            required: true,
            message: 'Please select your parent distributor User',
            trigger: 'change'
        }
    ]
})
function colseclose(formRef) {
    emits("close")
}
let listsort = ref([])
listsort.value = phoneCodeList.phoneCodeList?.sort((a, b) => {
    const charA = a.name.charAt(0).toUpperCase();
    const charB = b.name.charAt(0).toUpperCase();
    return charA.localeCompare(charB);
});
</script>
<template>
    <div class="editclass">
        <el-dialog :model-value="dialogFormVisible" style="padding: 40px;" :title="changeType == 'add' ? 'Add' : 'edit'"
            @close="colseclose">
            <el-form :model="formlist" ref="formRef" class="two-column-form" :rules="adminrule">
                <div class="form-row" v-if="changeType == 'add'">
                    <!-- 用户名称 -->
                    <el-form-item label="username" :label-width="formLabelWidth" prop="username">
                        <el-input v-model="formlist.username" placeholder="Please enter the username"
                            style="width: 200px;" />
                    </el-form-item>
                    <!-- 密码 -->
                    <el-form-item label="password" :label-width="formLabelWidth" prop="password">
                        <el-input v-model="formlist.password" autocomplete="off" placeholder="Please input the password"
                            style="width: 200px;" />
                    </el-form-item>
                </div>
                <div class="form-row">
                    <!-- 用户昵称 -->
                    <el-form-item label="nickname" :label-width="formLabelWidth" prop="nickname">
                        <el-input v-model="formlist.nickname" autocomplete="off"
                            placeholder="Please enter user nickname" style="width: 200px;" />
                    </el-form-item>

                    <!-- 邮箱 -->
                    <el-form-item label="email" :label-width="formLabelWidth" prop="email">
                        <el-input v-model="formlist.email" autocomplete="off" placeholder="Please enter your email"
                            type="email" style="width: 200px;" />
                    </el-form-item>
                </div>
                <div class="form-row">
                    <!-- 手机号 -->
                    <el-form-item label="phoneAreaCode" :label-width="formLabelWidth" prop="phoneAreaCode">
                        <el-select v-model="formlist.phoneAreaCode"
                            placeholder="Please select the area code for your phone number" style="width: 200px;">
                            <el-option v-for="item in listsort" :key="item.code" :label="item.name + '+' + item.code"
                                :value="item.code">
                                {{ item.name }} +{{ item.code }}
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="phoneNumber" :label-width="formLabelWidth" prop="phone">
                        <el-input v-model="formlist.phone" autocomplete="off"
                            placeholder="Please enter your phone number" style="width: 200px;" />
                    </el-form-item>
                </div>
                <div class="form-row">
                    <el-form-item label="location" :label-width="formLabelWidth" prop="area" class="no-error-style"
                        :show-message="false">
                        <div class="address-container">
                            <el-select v-model="formlist.contry" placeholder="Please select a country"
                                style="width: 200px; margin-right: 20px;" @change="handleCountryChange">
                                <el-option v-for="(item, index) in datasel" :key="index" :label="item.name"
                                    :value="item.name" />
                            </el-select>
                            <el-select v-model="formlist.addresszhou" placeholder="Please select a state or province"
                                style="width: 200px;" :disabled="!formlist.contry">
                                <el-option v-for="(state, index) in states" :key="index" :label="state.name"
                                    :value="state.name" />
                            </el-select>
                        </div>

                    </el-form-item>
                </div>
                <div class="form-row">
                    <!-- 地址 -->
                    <el-form-item label="address" :label-width="formLabelWidth" prop="account">
                        <el-input v-model="formlist.account" autocomplete="off"
                            placeholder="Please enter the user address" style="width: 200px;" />
                    </el-form-item>
                    <!-- 性别 -->
                    <el-form-item label="gender" :label-width="formLabelWidth" prop="gender">
                        <el-select v-model="formlist.gender" placeholder="Please select gender" style="width: 200px;">
                            <!-- <el-option label="男" value="1"></el-option>
                        <el-option label="女" value="0"></el-option> -->
                            <el-option v-for="item in [
                                { label: 'male', value: 1 },
                                { label: 'female', value: 0 }
                            ]" :key="item.value" :label="item.label" :value="item.value">
                                {{ item.label }}
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <div class="form-row" v-if="changeType == 'add' && isAdmin">
                    <!-- 上级分销商 -->
                    <el-form-item label="superior distributor" :label-width="formLabelWidth" prop="parentId">
                        <el-select v-model="formlist.parentId" placeholder="Please select the superior distributor"
                            style="width: 240px;">
                            <el-option v-for="item in distributorDropDownList" :key="item.userId" :label="item.nickname"
                                :value="item.userId">
                                {{ item.nickname }}
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="colseclose">cancel</el-button>
                    <el-button type="primary" @click="addsubmit(formRef)">
                        {{ changeType == "add" ? 'add' : 'edit' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>
<!-- <style lang="scss" scoped>
.two-column-form .form-row {
    display: flex;
    justify-content: space-between;
}

.two-column-form .el-form-item {
    width: 48%;
}
</style> -->
<style lang="scss" scoped>
.two-column-form .form-row {
    display: flex;
    justify-content: space-between;
}

.two-column-form .el-form-item {
    width: 48%;
}

.address-container {
    display: flex;
    align-items: center;
}

/* 调整表单标签宽度 */
.two-column-form :deep(.el-form-item__label) {
    width: 80px;
    text-align: right;
    padding-right: 12px;
}

/* 响应式设计 - 小屏幕时变为单列 */
@media (max-width: 768px) {
    .two-column-form .form-row {
        flex-direction: column;

        .el-form-item {
            width: 100%;
        }
    }

    .address-container {
        flex-direction: column;
        align-items: flex-start;

        .el-select {
            width: 100% !important;
            margin-right: 0 !important;
            margin-bottom: 10px;
        }
    }
}

.no-error-style.is-error .el-select {
    border-color: #dcdfe6 !important;
    /* 正常边框颜色 */
    box-shadow: none !important;
    /* 去掉错误阴影 */
}
</style>